class MandatoryTagLib {
    static namespace = "ps"

    def mandatory = {attrs, body ->
        out << "<font color='red'>[${message(code: 'taglib.mandatory')}]</font>"
    }

    def balance = {attrs ->
        if (attrs.amount < 0)
            out << "<font color='red'>${attrs.amount}</font>"
        else
            out << attrs.amount
    }

    def treeview = {attrs ->
        def root = attrs.remove('root')
        def id = attrs.remove('id')
        def ccsClass = attrs.remove('class')

        if (root) {
            out << "<ul id=\"$id\" class=\"$ccsClass\">"
            out << "<li>"
            renderNode(root, attrs, out)
            out << "</li>"
            out << "</ul>"
        }
    }

    void renderNode(node, attrs, out) {

        def childrenListName = attrs.'childrenListName'
        def leafListName = attrs.'leafListName'

        out << "<span class=\"folder\">"
        renderFolder(node, attrs, out)
        out << "</span>"

        if ((childrenListName && node."$childrenListName") || (leafListName && node."$leafListName")) {
            out << "<ul>"
            if(childrenListName && node."$childrenListName")
                node."$childrenListName"?.each {
                    out << "<li>"
                    renderNode(it, attrs, out)
                    out << "</li>"
                }
            if(leafListName && node."$leafListName")
                node."$leafListName"?.each {
                    out << "<li>"
                    out << "<span class=\"file\">"
                    renderFile(it, attrs, out)
                    out << "</span>"
                    out << "</li>"
                }
            out << "</ul>"
        }
    }

    void renderFile(node, attrs, out){
        def fileController = attrs.'fileController'
        def fileAction = attrs.fileAction?attrs.fileAction:"show"
        String displayText = "$node.name"
        if(fileController != null) {
            String link = createNodeLink(displayText, fileController, fileAction, node)
            out << link
        }
        else
            out << displayText
    }

    void renderFolder(node, attrs, out){
        def folderController = attrs.'folderController'
        def folderAction = attrs.folderAction?attrs.folderAction:"show"
        String displayText = "$node.name"
        if(folderController != null) {
            String link = createNodeLink(displayText, folderController, folderAction, node)
            out << link
        }
        else
            out << displayText

    }

    def createNodeLink(String displayText, folderController, folderAction, node) {
        return "<a href='${createLink(controller: folderController, action: folderAction, id: node.id).encodeAsHTML()}' id='${node.id}'>$displayText</a> "
    }
}
